package com.example.gkcircle.fragment;

import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.example.gkcircle.App;
import com.example.gkcircle.BaseFragment;
import com.example.gkcircle.R;
import com.example.gkcircle.activity.LostAndFoundActivity;
import com.example.gkcircle.adapter.HomeAdapter;
import com.example.gkcircle.adapter.WishAdapter;
import com.example.gkcircle.bean.Wish;
import com.example.gkcircle.db.DBUtil;
import com.example.gkcircle.library.object.GKUser;
import com.example.gkcircle.utils.ActivityUtil;
import com.example.gkcircle.utils.DateUtil;
import com.example.gkcircle.utils.HttpClientUtil;
import com.example.gkcircle.utils.ThreadPoolUtils;
import com.example.gkcircle.utils.ToastFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

/**
 * 首页Fragment
 * @author ZhouHua
 * created at 15/12/21 上午12:54
*/
public class HomeFragment extends BaseFragment implements View.OnClickListener
{

	private SwipeRefreshLayout mSwipe;
	private ListView mListView;
    private View mHeaderView;
    private LinearLayout mGrade;
    private LinearLayout mLost;
    private HomeAdapter mAdapter;
    private boolean isRefreshing;

	@Override
	protected int setLayout() {
		return R.layout.fragment_home;
	}

	@Override
	protected void initView(View view) {
        mSwipe=(SwipeRefreshLayout)view.findViewById(R.id.home_swipe);
		mListView = (ListView) view.findViewById(R.id.home_listview);
        mSwipe.setColorSchemeColors(getResources().getColor(R.color.main), getResources().getColor(R.color.love), getResources().getColor(R.color.wish));

        //add headerView
        if (mHeaderView == null) {
            mHeaderView = LayoutInflater.from(getActivity()).inflate(R.layout.home_header, null, false);
            mListView.addHeaderView(mHeaderView, null, false);
            mListView.setAdapter(null);
        }
        //init headerView
        mGrade = (LinearLayout) mHeaderView.findViewById(R.id.home_header_grade_layout);
        mLost = (LinearLayout) mHeaderView.findViewById(R.id.home_header_lost_layout);
	}

	@Override
	protected void initListener() {
        mGrade.setOnClickListener(this);
        mLost.setOnClickListener(this);
        mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isRefreshing) {
                    isRefreshing = true;
                    setData();
                }
            }
        });
	}

	@Override
	protected void setData() {
        setLeftBtnBackgound(R.mipmap.logo);
        setRightBtnBackgound(R.mipmap.home_notice_spot);
        setmTitleHide(true);
        mSwipe.setRefreshing(true);
        //获取数据
        getData(new IGetDataListener() {
            @Override
            public void complete(List<AVObject> list) {
                if (App.mHomeList == null) {
                    App.mHomeList = new ArrayList<Wish>();
                } else {
                    if (isRefreshing) App.mHomeList.clear();
                }
                for (int i = 0; i < list.size(); i++) {
                    Wish wish = new Wish();
                    wish.setUser(list.get(i).getAVUser("user"));
                    wish.setContent(list.get(i).get("content").toString());
                    wish.setCreatedAt(DateUtil.getLastMinTime(list.get(i).getDate("createdAt").getTime()));
                    wish.setLikeCount(list.get(i).getAVObject("like").getInt("likeCount"));
                    wish.setLikesObjectId(list.get(i).getAVObject("like").getObjectId());
                    wish.setObjectId(list.get(i).getObjectId());
                    wish.setIsLike(DBUtil.getInstance(getActivity()).getLikeWish(wish));
                    AVFile avFile = list.get(i).getAVFile("photo");
                    if (null != avFile) {
                        if (null != avFile.getMetaData("width") && null != avFile.getMetaData("height")) {
                            wish.setPhotoWidth(Integer.parseInt(avFile.getMetaData("width").toString()));
                            wish.setPhotoHeight(Integer.parseInt(avFile.getMetaData("height").toString()));
                        }
                        wish.setPhotoUrl(avFile.getUrl());
                    }
                    App.mHomeList.add(wish);
                }
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                    mSwipe.setRefreshing(false);
                    isRefreshing = false;
                    return;
                }
                mSwipe.setRefreshing(false);
                mAdapter=new HomeAdapter(getActivity(),App.mHomeList);
                // set adapter
                mListView.setAdapter(mAdapter);
            }
        });

	}



    //获取数据
    public IGetDataListener getDataListener;

    private interface IGetDataListener {
        void complete(List<AVObject> list);
    }

    private void getData(final IGetDataListener getDataListener) {
        this.getDataListener = getDataListener;
        AVQuery<AVObject> query = new AVQuery<>("Wish");
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.setLimit(10);
        query.orderByDescending("createdAt");
        query.include("user");
        query.include("like");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list.size() > 0) {
                        if (dataFlag) getDataListener.complete(list);
                        else return;
                    } else {
                        mSwipe.setRefreshing(false);
                        ToastFactory.getToast(getActivity(), getResources().getString(R.string.no_more_data)).show();
                    }
                } else {
                    mSwipe.setRefreshing(false);
                    ToastFactory.getToast(getActivity(), getResources().getString(R.string.connection_error)).show();
                }
            }
        });
    }


    public String random(){
        String num="";
        for(int i=0;i<4;i++){
            num=num+(int)(Math.floor(Math.random()*10));
        }
        Log.i("test", "random: "+num);
        return num;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.home_header_grade_layout:
                ToastFactory.getToast(getActivity(),"敬请期待").show();
                if(true)return;
                final String url="http://enet.10000.gd.cn:10001/login.do";

                final HashMap<String, String> param1 = new HashMap<String, String>();
                param1.put("edubas", "119.146.248.2");
                param1.put("eduuser","183.47.64.192");
                param1.put("rand", random());
                param1.put("userName1", "13392964698");
                param1.put("password1", "6666");

                final HashMap<String, String> param2 = new HashMap<String, String>();
                param2.put("edubas", "119.146.248.2");
                param2.put("eduuser", "183.47.64.241");
                param2.put("rand", random());
                param2.put("userName1", "13392964698");
                param2.put("password1", "6666");

                final HashMap<String, String> param3 = new HashMap<String, String>();
                param2.put("edubas", "119.146.248.2");
                param2.put("eduuser", "183.47.67.176");
                param2.put("rand", random());
                param2.put("userName1", "13392964698");
                param2.put("password1", "6666");


                final long nowTime=System.currentTimeMillis();

                ThreadPoolUtils.execute(new Runnable() {
                    @Override
                    public void run() {
                        HttpClientUtil.RequestResult result3 = HttpClientUtil.post(url, null, param3);
                        long currentTime = System.currentTimeMillis();
                        Log.i("test", "run: jingpei " + (currentTime - nowTime));
                    }
                });


                ThreadPoolUtils.execute(new Runnable() {
                    @Override
                    public void run() {

                        HttpClientUtil.RequestResult result1 = HttpClientUtil.post(url, null, param1);
                        long currentTime=System.currentTimeMillis();
                        Log.i("test", "run: zhouhua "+(currentTime-nowTime));
                    }
                });

                ThreadPoolUtils.execute(new Runnable() {
                    @Override
                    public void run() {
                        HttpClientUtil.RequestResult result2 = HttpClientUtil.post(url, null, param2);
                        long currentTime = System.currentTimeMillis();
                        Log.i("test", "run: fazai " + (currentTime - nowTime));
                    }
                });

                break;
            case R.id.home_header_lost_layout:
                ActivityUtil.startActivity(getActivity(), LostAndFoundActivity.class);
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        isRefreshing=true;
    }
}
